//
//  RejectRefundVC.m
//  jingdongfang
//
//  Created by MTiMac02 on 2018/1/13.
//  Copyright © 2018年 LJL. All rights reserved.
//

#import "RejectRefundVC.h"
#import "IGOSSManager.h"
#import "IWTextView.h"
#import "IGRejectRefundApi.h"
#import "OrderXQViewController.h"
#import "MyOrderViewController.h"
#import "MyBuyViewController.h"

@interface RejectRefundVC ()
{
    NSString *money;
    NSString *resonStr;
    IWTextView *textView;
    UIButton *img1;
    UIButton *img2;
    UIButton *img3;
    UIImageView *imgView1;
    UIImageView *imgView2;
    UIImageView *imgView3;
    UIButton *sure;
}
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, strong) NSMutableArray *picParams;
@property(nonatomic,strong)IGRejectRefundApi *rejectApi;
@end

@implementation RejectRefundVC
#pragma mark -懒加载
- (NSMutableArray *)selectedAssets
{
    if (!_selectedAssets) {
        _selectedAssets = [[NSMutableArray alloc] init];
    }
    return _selectedAssets;
}
- (NSMutableArray *)picParams {
    if (!_picParams) {
        _picParams = [[NSMutableArray alloc] init];
    }
    return _picParams;
}
#pragma mark -生命周期
- (void)viewDidLoad {
    self.title=NSLocalizedString(@"Refund Processing", nil);
    self.tableView.backgroundColor=[UIColor c2Color];
    self.tableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled=NO;
    /** accessToken有过期时间，所以在每次需要的时候重新请求 */
    [[IGOSSManager sharedManager] requestOssToken:IGAliYunFolderTypeRefund];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGestureRecognizer];
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, GSCALE(90))];
    sure = [UIButton buttonWithType:UIButtonTypeCustom];
    sure.layer.cornerRadius = 20;
    sure.layer.masksToBounds = YES;
    sure.backgroundColor = [UIColor appColor];
    sure.frame = CGRectMake(0, 15, KSCALE(1100), 45);
    sure.titleLabel.font = [UIFont systemFontOfSize:16];
    [sure setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [sure setTitle:@"提 交" forState:UIControlStateNormal];
    [sure setTitle:NSLocalizedString(@"Submit", nil) forState:UIControlStateNormal];
    [sure addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    sure.centerX = footer.width/2;
    [footer addSubview:sure];
    self.tableView.tableFooterView=footer;
    [super viewDidLoad];
    
}

#pragma mark------UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.separatorInset = UIEdgeInsetsMake(0, 15, 0, 0);
    cell.textLabel.font = [UIFont font16];
    cell.detailTextLabel.font = [UIFont font12];
    cell.textLabel.textColor=[UIColor c4Color];
    if (indexPath.section==0) {
        CGFloat h=[self tableView:tableView heightForRowAtIndexPath:indexPath];
        cell.backgroundColor=[UIColor c3Color];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        textView = [[IWTextView alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH-15, h)];
        textView.font = [UIFont systemFontOfSize:15];
        textView.tag = indexPath.row;
        textView.placeholder = NSLocalizedString(@"Please Input Reason(s) for Refund Refusal", nil);
        textView.text = resonStr;
        textView.keyboardType = UIKeyboardTypeDefault;
        [cell.contentView addSubview:textView];
    }
    if(indexPath.section==1){
        cell.backgroundColor=[UIColor c2Color];
        CGFloat gap=(KSCREENWIDTH-GSCALE(300)-30)/2;
        img1=[[UIButton alloc]initWithFrame:CGRectMake(15, 0, GSCALE(100), GSCALE(100))];
        img1.backgroundColor=[UIColor clearColor];
        imgView1=[[UIImageView alloc]initWithFrame:CGRectMake(15, 0, GSCALE(100), GSCALE(100))];
        imgView1.image=[UIImage imageNamed:@"upload_image"];
        [img1 addTarget:self action:@selector(imgBtnClick:) forControlEvents: UIControlEventTouchUpInside];
        imgView1.userInteractionEnabled=YES;
        [imgView1 addSubview:img1];
        
        imgView2=[[UIImageView alloc]initWithFrame:CGRectMake(imgView1.right+gap, 0, GSCALE(100), GSCALE(100))];
        imgView2.image=[UIImage imageNamed:@"upload_image"];
        img2=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, GSCALE(100), GSCALE(100))];
        img2.backgroundColor=[UIColor clearColor];
        [img2 addTarget:self action:@selector(imgBtnClick:) forControlEvents: UIControlEventTouchUpInside];
        imgView2.userInteractionEnabled=YES;
        [imgView2 addSubview:img2];
        imgView2.hidden=YES;
        imgView3=[[UIImageView alloc]initWithFrame:CGRectMake(imgView2.right+gap, 0, GSCALE(100), GSCALE(100))];
        imgView3.image=[UIImage imageNamed:@"upload_image"];
        img3=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, GSCALE(100), GSCALE(100))];
        img3.backgroundColor=[UIColor clearColor];
        [img3 addTarget:self action:@selector(imgBtnClick:) forControlEvents: UIControlEventTouchUpInside];
        imgView3.userInteractionEnabled=YES;
        [imgView3 addSubview:img3];
        imgView3.hidden=YES;
        
        [cell.contentView addSubview:imgView1];
        [cell.contentView addSubview:imgView2];
        [cell.contentView addSubview:imgView3];
    }
    return cell;
}

#pragma mark------UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        CGFloat h1 = [self tableView:tableView heightForHeaderInSection:section];
        UIView *view1=[[UIView alloc]initWithFrame:CGRectZero];
        view1.backgroundColor=[UIColor c2Color];
        view1.left=tableView.left+15;
        view1.size=CGSizeMake(KSCREENWIDTH-15, h1);
        UILabel *lable1=[[UILabel alloc]initWithFrame:CGRectZero];
        lable1.backgroundColor=[UIColor c2Color];
        lable1.text=NSLocalizedString(@"Reason(s) for Refund Refusal(Compulsory)", nil);
        [lable1 sizeToFit];
        lable1.y=(view1.height-lable1.height)/2;
        lable1.x=view1.x;
        lable1.font=[UIFont systemFontOfSize:15];
        lable1.textColor=[UIColor grayColor];
        lable1.textAlignment=NSTextAlignmentLeft;
        [view1 addSubview:lable1];
        return view1;
    }
    if (section==1) {
        CGFloat h2 = [self tableView:tableView heightForHeaderInSection:section];
        UIView *view=[[UIView alloc]initWithFrame:CGRectZero];
        view.backgroundColor=[UIColor c2Color];
        view.left=tableView.left+15;
        view.size=CGSizeMake(KSCREENWIDTH-15, h2);
        UILabel *lable=[[UILabel alloc]initWithFrame:CGRectZero];
        lable.backgroundColor=[UIColor c2Color];
        lable.text=NSLocalizedString(@"Upload Voucher(s)(Optional, 3 Vouchers Max)", nil);
        [lable sizeToFit];
        lable.y=(view.height-lable.height)/2;
        lable.x=view.x;
        lable.font=[UIFont systemFontOfSize:15];
        lable.textColor=[UIColor grayColor];
        lable.textAlignment=NSTextAlignmentLeft;
        [view addSubview:lable];
        return view;
    }
    return nil;
}

#pragma mark------提交拒绝退款处理
-(void)sureAction:(UIButton *)btn
{
    sure.enabled =NO;
    [self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:1.0f];//防止重复点击
    if (textView.text.length>30) {
        [self presentMessageTips:NSLocalizedString(@"30 Characters Max", nil)];
        return;
    }
    if (textView.text.length<=0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Reason(s) for Refusal", nil)];
        return;
    }
    if (_selectedAssets.count == 0 || _selectedAssets == nil)
    {
        [self publishTopicRequest];
    } else
    {
        [self asyncPutImages:_selectedAssets];
    }
}
-(void)changeButtonStatus{
    sure.enabled =YES;
}
#pragma mark ---- 上传照片
-(void)imgBtnClick:(UIButton *)btn
{
    if (btn==img1) {
        [self selectPhoto:@"0"];
    }
    if (btn==img2) {
        [self selectPhoto:@"1"];
    }
    if (btn==img3) {
        [self selectPhoto:@"2"];
    }
}
-(void)publishTopicRequest{
    self.rejectApi=[[IGRejectRefundApi alloc]init];
    _rejectApi.oid=self.oid;
    _rejectApi.refundReason=textView.text;
    _rejectApi.refundProof=self.picParams;
    __weak typeof(self) weakSelf = self;
    [self.rejectApi startWithDecodeClass:[IGRejectRefundResp class]CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [weakSelf presentMessageTips:NSLocalizedString(@"Application Successful !", nil)];
            int index = (int)[[self.navigationController viewControllers]indexOfObject:self];
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index -2)] animated:YES];
        } else {
            [weakSelf presentMessageTips:NSLocalizedString(@"Application Failed !", nil)];
        }
    }];
}
- (void)selectPhoto:(NSString *)index {
    @KWeakObj(self)
    [IGPermissionUtil ig_showActionSheetWithCameraBlock:^{
        [IGTakePhotosUtil ig_showImagePickerControllerWithImagePickerBlock:^(NSDictionary<NSString *,id> * _Nullable info) {
            if (info) {
                UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
                image = [image fixOrientation];
                [selfWeak.selectedAssets addObjectsFromArray:@[image]];
                if ([index integerValue]==0) {
                    if (imgView1.image!=nil) {
                        [selfWeak.selectedAssets removeObjectsInRange:NSMakeRange(0, _selectedAssets.count)];
                        imgView1.image=image;
                        imgView2.hidden=NO;
                        [selfWeak.selectedAssets addObject:image];
                        if (imgView2.image!=nil&&imgView2.image.size.width!=84&&imgView2.image.size.height!=84) {
                            [selfWeak.selectedAssets addObject:imgView2.image];
                        }
                        if (imgView3.image!=nil&&imgView3.image.size.width!=84&&imgView3.image.size.height!=84) {
                            [selfWeak.selectedAssets addObject:imgView3.image];
                        }
                    }else{
                    imgView1.image=image;
                    imgView2.hidden=NO;
                    }
                }
                if ([index integerValue]==1) {
                    if (imgView2.image!=nil) {
                        [selfWeak.selectedAssets removeObjectsInRange:NSMakeRange(1, _selectedAssets.count-1)];
                        imgView2.image=image;
                        imgView3.hidden=NO;
                        [selfWeak.selectedAssets addObject:image];
                        if (imgView3.image!=nil&&imgView3.image.size.width!=84&&imgView3.image.size.height!=84) {
                            [selfWeak.selectedAssets addObject:imgView3.image];
                        }
                    }else{
                    imgView2.image=image;
                    imgView3.hidden=NO;
                    }
                }
                if ([index integerValue]==2) {
                    if (imgView3.image!=nil) {
                        [selfWeak.selectedAssets removeObjectsInRange:NSMakeRange(2, _selectedAssets.count-2)];
                        imgView3.image=image;
                        [selfWeak.selectedAssets addObject:image];
                    }else{
                    imgView3.image=image;
                    }
                }
            }
        }];
    } photoBlock:^{
        [IGTakePhotosUtil ig_showAssetsPickerControllerWithMaximumNumberOfSelection:1 assetsPickerBlock:^(NSArray<UIImage *> * _Nullable assets) {
            if (assets.count != 0) {
                [selfWeak.selectedAssets addObjectsFromArray:assets];
                if ([index integerValue]==0)
                {
                    if (imgView1.image!=nil) {
                        [selfWeak.selectedAssets removeObjectsInRange:NSMakeRange(0, _selectedAssets.count)];
                        imgView1.image=assets[0];
                        imgView2.hidden=NO;
                        [selfWeak.selectedAssets addObject:assets[0]];
                        if (imgView2.image!=nil&&imgView2.image.size.width!=84&&imgView2.image.size.height!=84) {
                            [selfWeak.selectedAssets addObject:imgView2.image];
                        }
                        if (imgView3.image!=nil&&imgView3.image.size.width!=84&&imgView3.image.size.height!=84) {
                            [selfWeak.selectedAssets addObject:imgView3.image];
                        }
                    }else{
                    imgView1.image=assets[0];
                    imgView2.hidden=NO;
                    }
                }
                if ([index integerValue]==1)
                {
                    if (imgView2.image!=nil) {
                        [selfWeak.selectedAssets removeObjectsInRange:NSMakeRange(1, _selectedAssets.count-1)];
                        imgView2.image=assets[0];
                        imgView3.hidden=NO;
                        [selfWeak.selectedAssets addObject:assets[0]];
                        if (imgView3.image!=nil&&imgView3.image.size.width!=84&&imgView3.image.size.height!=84) {
                            [selfWeak.selectedAssets addObject:imgView3.image];
                        }
                    }else{
                    imgView2.image=assets[0];
                    imgView3.hidden=NO;
                    }
                }
                if ([index integerValue]==2)
                {
                    if (imgView3.image!=nil) {
                        [selfWeak.selectedAssets removeObjectsInRange:NSMakeRange(2, _selectedAssets.count-2)];
                        imgView3.image=assets[0];
                        [selfWeak.selectedAssets addObject:assets[0]];
                    }else{
                    imgView3.image=assets[0];
                    }
                }
                
            }
        }];
    }];
}
- (void)asyncPutImages:(NSArray *)images {
    __weak typeof(self) weakSelf = self;
    [[IGOSSManager sharedManager] asyncPutImages:images withCompleteBlock:^(NSArray *params, NSArray *urls)
     {
         if (params.count != 0)
         {
             [weakSelf.picParams addObjectsFromArray:params];
                 [weakSelf publishTopicRequest];
         } else {
//             [weakSelf presentMessageTips:@"发布失败!"];
             [weakSelf presentMessageTips:NSLocalizedString(@"Publication failed!", nil)];
         }
     }];
}
-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [textView resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
